// src/services/sync.js
export function addToOfflineQueue(operation) {
  let offlineQueue = JSON.parse(localStorage.getItem('offlineQueue')) || [];
  offlineQueue.push(operation);
  localStorage.setItem('offlineQueue', JSON.stringify(offlineQueue));
}

export async function syncWithServer() {
  let offlineQueue = JSON.parse(localStorage.getItem('offlineQueue')) || [];
  while (offlineQueue.length > 0) {
    const operation = offlineQueue.shift();
    try {
      await fetch('/api/diaries', {
        method: operation.method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(operation.body),
      });
    } catch (error) {
      offlineQueue.unshift(operation);
      break;
    }
  }
  localStorage.setItem('offlineQueue', JSON.stringify(offlineQueue));
}

window.addEventListener('online', () => syncWithServer());
